/*
 * Copyright 2010 original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.alertleon;

import com.configleon.configurer.Config;
import static com.alertleon.AlertConfiguration.*;
import org.springframework.util.StringUtils;

public class AlertConfigurationFactory {

    private final String queueName;

    public AlertConfigurationFactory() {
        this(null);
    }

    public AlertConfigurationFactory(String queueName) {
        this.queueName = queueName;
    }

    public AlertConfiguration create() {
        AlertConfigurationBuilder builder = new AlertConfigurationBuilder();

        String enabled = getValue(ENABLED_PROP);
        if (StringUtils.hasText(enabled)) {
            builder.enabled(Boolean.valueOf(enabled));
        }

        String delay = getValue(DELAY_PROP);
        if (StringUtils.hasText(delay)) {
            builder.delay(Integer.valueOf(delay));
        }

        String port = getValue(PORT_PROP);
        if (StringUtils.hasText(port)) {
            builder.port(Integer.valueOf(port));
        }

        builder.smtpServer(getValue(SMTP_SERVER_PROP));
        builder.toAddress(getValue(TO_ADDRESS_PROP));
        builder.fromAddress(getValue(FROM_ADDRESS_PROP));
        builder.subject(getValue(SUBJECT_PROP));
        builder.excludeClasses(getValue(EXCLUDE_CLASS_PROP));

        return builder.build();
    }

    /**
     * Try to get a configuration value based on the queue name. If there is not 
     * one then fall back on the default.
     */
    private String getValue(String name) {
        if (StringUtils.hasText(queueName)) {
            String[] split = name.split("\\.");
            String customName = split[0] + "." + queueName + '.' + split[1];
            String value = Config.getProperty(customName);
            if (StringUtils.hasText(value)) {
                return value;
            }
        }

        return Config.getProperty(name);
    }
}
